<?php
namespace app\api\controller;

use think\Db;
use http\Http;
use app\common\model\Sms;
use http\AliSendSms;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config;
use app\common\service\AlipayService;

use think\Exception;

//无需验证token
class Login extends App
{
    public function regeister()
    {
        $data['username'] = $this->request->post("phone");
        $data['phone'] = $this->request->post("phone");
        $data['nickname'] = $this->request->post("phone");
        $data['headimgurl'] = config('app_host').'/images/default_head.png';
        $data['password'] = $this->request->post("password",'','trim');
        $data['yzm'] = $this->request->post("yzm");
        $validate = new \app\api\validate\Member();
        if(!$validate->scene('reg')->check($data)){
            return $this->show(2001,$validate->getError());
        }
        $repassword = $this->request->post("repassword",'','trim');
		if($data['password'] != $repassword){
			return $this->show(2001,'两次密码不一致');
		}
        
        $smsinfo = Sms::where('phone='.$data['username'].' and event="reg"')->order('id','DESC')->find();
        $nowtime = time();
        if(empty($smsinfo) || $smsinfo['code'] != $data['yzm'] || ($nowtime-$smsinfo['createtime']) >300){
            //return $this->show(2001,"验证码错误");
        }
        $data['pass_key'] = self::str_rand(10);
        $data['password'] = md5($this->request->post("password").$data['pass_key']);
        $data['create_time'] = time();
		unset($data['yzm']);
        if( Db::name("member")->insert($data) ){
            return $this->show(1,"注册成功");
        }else{
            return $this->show(2002, "fail");
        }
    }

    /**
     * 登录
     * @return false|string
     */
    public function login()
    {
        $phone = $this->request->post("phone");
        $password = $this->request->post("password");
        if($phone == "" || $password == "" ){
            return $this->show(2001,"请填写手机号和密码");
        }
        
        $userInfo = Db::name("member")->field('id,password,pass_key')->where(array("username"=>$phone,'status'=>1))->find();
        if( !$userInfo ){
            return $this->show(2001,"账号不存在！", '');
        }
        if($userInfo['password'] == md5($password.$userInfo['pass_key'])){
            $user_id = $userInfo['id'];
            $user_token = Db::name("member_token")->where(array('user_id'=>$user_id))->find();
            if( $user_token ){
                $expire_time = time()+604800;
                $token = self::settoken();
                $res = Db::name("member_token")->where(array('user_id'=>$user_id))->update(['expire_time'=>$expire_time,'token'=>$token]);
                if($res){
                    $return_data['user_id'] = $user_id;
                    $return_data['token'] = $token;
                    return $this->show(1,"登录成功", $return_data);
                }else{
                    return $this->show(1004,"token错误！", '');
                }
            }else{  //如果是第一次登录创建token
                $data['user_id'] = $user_id;
                $data['token'] = self::settoken();
                $data['expire_time'] = strtotime("+7 days");
                $data['create_time'] = time();
                $id = Db::name("member_token")->insertGetId($data);
                $res_token = Db::name("member_token")->find($id);
                if($res_token){
                    $return_data['user_id'] = $res_token['user_id'];
                    $return_data['token'] = $res_token['token'];
                    return $this->show(1,"登录成功", $return_data);
                }else{
                    return $this->show(1004,"token错误！", '');
                }
            }
        }else{
            return $this->show(1002,"密码错误，请重试！", '');
        }
    }
    
    public function login_yzm()
    {
        $phone = $this->request->post("phone");
        $yzm = $this->request->post("yzm");
        if($phone == "" || $yzm == "" ){
            return $this->show(2001,"请填写手机号和验证码");
        }
		$smsinfo = Sms::where('phone='.$phone.' and event="log"')->order('id','DESC')->find();
        $nowtime = time();
        if(empty($smsinfo) || $smsinfo['code'] != $yzm || ($nowtime-$smsinfo['createtime']) >300){
            //return $this->show(2001,"验证码错误");
        }
        $userInfo = Db::name("member")->field('id,password,pass_key')->where(array("username"=>$phone,'status'=>1))->find();
        if(empty($userInfo) ){
            return show(2001,"账号不存在！", '');
        }else{
            $user_id = $userInfo['id'];
			$user_token = Db::name("member_token")->where(array('user_id'=>$user_id))->find();
            if( $user_token ){
                $expire_time = time()+604800;
                $token = self::settoken();
                $res = Db::name("member_token")->where(array('user_id'=>$user_id))->update(['expire_time'=>$expire_time,'token'=>$token]);
                if($res){
                    $return_data['user_id'] = $user_id;
                    $return_data['token'] = $token;
                    return show(1,"登录成功", $return_data);
                }else{
                    return show(1004,"token错误！", '');
                }
            }else{  //如果是第一次登录创建token
                $data['user_id'] = $user_id;
                $data['token'] = self::settoken();
                $data['expire_time'] = strtotime("+7 days");
                $data['create_time'] = time();
                $id = Db::name("member_token")->insertGetId($data);
                $res_token = Db::name("member_token")->find($id);
                if($res_token){
                    $return_data['user_id'] = $res_token['user_id'];
                    $return_data['token'] = $res_token['token'];
                    return show(1,"登录成功", $return_data);
                }else{
                    return show(1004,"token错误！", '');
                }
            }
		}
    }
	
	//微信登录
    public function wxlogin(){

        $appid = 'wxaec273f332976f16';
        $secret = 'db6cf4d65fdca5fbbcc9016dc30b5962';
        $code = $this->request->post("code");
        if (!$code) {
			return show(2001,"确少参数code！", '');
        }
        if (!$appid || !$secret) {
			return show(2002,"接口出错！", '');
        }

        $get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$get_token_url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
		
		$res = json_decode($res,true);
		if(!empty($res['errcode'])){
			return show(2002,$res['errmsg'], '');
		}
		unset($res['session_key']);
		if(empty($res['openid'])){
			return show(2002,"接口获取失败！", '');
		}
		$openid = $res['openid'];
		
		$user_info = Db::name('member')->where('openid',$openid)->field('id,username')->find();
		
		if (!empty($user_info)) {
            $user_id = $user_info['id'];
			
            return $this->login_token_wx($user_id,$openid);
        }else{
			$return_data['openid'] = $openid;
			return show(1,"授权成功,请完善信息", $return_data);
			
		}
    }
	
	//微信登录-完善信息
    public function wxlogin_information()
    {
        $openid = $this->request->post("openid");
        $phone = $this->request->post("phone");
        $code = $this->request->post("code");
        $yzm = $this->request->post("yzm");
		if(empty($openid)){
			return show(2001,"缺少参数openid！", '');
		}
		if(empty($phone)){
			return show(2001,"请填写手机号！", '');
		}
		if(empty($yzm)){
			return show(2001,"请填写验证码！", '');
		}
		
		$smsinfo = Sms::where('phone='.$phone.' and event="wx"')->order('id','DESC')->find();
		$nowtime = time();
		if(empty($smsinfo) || $smsinfo['code'] != $yzm || ($nowtime-$smsinfo['createtime']) >300){
			return show(2001,"验证码错误！", '');
		}
		$user_info = Db::name('member')->where(array("username"=>$phone))->field('id,username')->find();
		
		if(!empty($user_info)){//已有账号
			
			$row = Db::name('member')->where(array("id"=>$user_info['id']))->update(['openid'=>$openid]);
			$user_id = $user_info['id'];
			return $this->login_token_wx($user_id,$openid);
		}else{
			
			$data['username'] = $phone;
			$data['phone'] = $phone;
			$data['nickname'] = $phone;
			$data['headimgurl'] = config('app_host').'/images/default_head.png';
			$data['create_time'] = time();
			$data['username'] = $phone;
			$data['openid'] = $openid;
			$user_id = Db::name("member")->insertGetId($data);
			return $this->login_token_wx($user_id,$data['openid']);
		}
        
    }
	public function login_token_wx($user_id,$openid=''){
		$user_token = Db::name("member_token")->where(array('user_id'=>$user_id))->find();
		if( $user_token ){
			$expire_time = time()+604800;
			$token = self::settoken();
			$res = Db::name("member_token")->where(array('user_id'=>$user_id))->update(['expire_time'=>$expire_time,'token'=>$token]);
			if($res){
				$return_data['user_id'] = $user_id;
				$return_data['token'] = $token;
				$return_data['openid'] = $openid;
				return show(1,"登录成功", $return_data);
			}else{
				return show(2002,"token生成错误,请重试！", '');
			}
		}else{  //如果是第一次登录创建token
			$dataT['user_id'] = $user_id;
			$dataT['token'] = self::settoken();
			$dataT['expire_time'] = strtotime("+7 days");
			$dataT['create_time'] = time();
			$id = Db::name("member_token")->insertGetId($dataT);
			$res_token = Db::name("member_token")->find($id);
			if($res_token){
				$return_data['user_id'] = $res_token['user_id'];
				$return_data['token'] = $res_token['token'];
				$return_data['openid'] = $openid;
				return show(1,"登录成功,请完善信息", $return_data);
			}else{
				return show(2002,"token错误,请重试！", '');
			}
		}
	}
	
	
    //验证码
    public function send_sms()
    {
        try{
			$phone = $this->request->post("phone");
			$type = $this->request->post("type");
            if (empty($phone) || empty($type)) {
                throw new Exception('请填写手机号和类型');
            }
            if(!preg_match("/^1[3456789]{1}\d{9}$/",$phone)){
                throw new Exception('请填写正确的手机号');
            }
            
            if(!in_array($type,['reg','log','forget','wx'])){
                 throw new Exception('类型不正确');
            }
            $smsinfo = Db::name('sms')->where('phone',$phone)->order('id','DESC')->find();
            $nowtime = time();
            if(!empty($smsinfo)){
                if($nowtime - $smsinfo['createtime']<120){
                    throw new Exception('发送频繁');
                }
            }
           
            $content = mt_rand(111111, 999999);
            $argv = [
                "phoneNumbers" => $phone,
                "signName" => "湖北明德文创教育管理集团",
                "templateCode" => "SMS_317910277",
                "templateParam" => '{"code":"'.$content.'"}'
            ];
            $response = AliSendSms::main($argv);
			
            //dump($response);die;
            if($response['code'] !== 'OK'){
                //throw new Exception('短信发送失败');
                return show(2001,$response['message']);
            }else{
                $SmsModel = new Sms;
                $data['phone'] = $phone;
                $data['code'] = $content;
                $data['event'] = $type;
                $data['ip'] = request()->ip();
                $data['createtime'] = time();
                $res = $SmsModel->allowField(true)->save($data);
                return show(1,"发送成功");
            }
			
        }
        catch(Exception $e){
            //$e->getMessage().$e->getFile().$e->getLine()
            return show(2001,$e->getMessage(), '');
        }
       
    }
    
    
    /**
     * 生成指定长度随机字符串
     * @param int $length
     * @param string $char
     * @return bool|string
     */
    public function str_rand($length = 32, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
        if(!is_int($length) || $length < 0) {
            return false;
        }
        $string = '';
        for($i = $length; $i > 0; $i--) {
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }
        return $string;
    }
    /**
     * 生成token
     * @return string
     */
    public function settoken(){
        $str = md5(uniqid(md5(microtime(true)),true));  //生成一个不会重复的字符串
        $str = sha1($str);  //加密
        return $str;
    }
	
	
    public function alnotify(\think\Request $request){
        //$parameters = file_get_contents("php://input");
		$parameters = $request->post(); // 获取POST请求参数
		
		//setLog('alinotify','回调参数:'.json_encode($parameters));
		if (!empty($parameters['fund_bill_list'])) {
			$parameters['fund_bill_list'] = json_encode(json_decode($parameters['fund_bill_list'], true));
		}
		
		
//$parameters = '{"gmt_create":"2025-06-10 22:39:07","charset":"UTF-8","gmt_payment":"2025-06-10 22:39:18","notify_time":"2025-06-10 22:39:18","subject":"\u8d2d\u4e70\u670d\u52a1","sign":"X1gpKWIsJhu7+tZsFkdFMBj6cQLr7R0CKATvcLtwafivgRPTIWfvlHKAczcs9QpusuZaX2tAmX4TCPHMUpSeSU8vGcTrj0OkwEVr9wkAJGmSjYmifsD+xHmWfn8BVx1rerwOZlJ5u3TRZSVmN7NR5UKES+hjDvC6HNkf1mvQdL4GTZevs0u\/GUBXfgHyGBG0QmraOmw9YCj68PwnGCj2RqRpYsjrP9pHZvkBPy3361PNJulsRX8Qs1xHC5NG\/JCp3y3aKzYlxhjVJHkmd3846C4nTj2ssZYPB11lXGWHLX07EoSktt4rmXOI2hSNRoci03Q1d1dvaOwoBUX4xcVydw==","merchant_app_id":"2021005151606716","buyer_open_id":"021okUzhE-wn3a6rhI0EKYhM6ntirAFX3fXJhzJGO0saZg4","invoice_amount":"0.01","version":"1.0","notify_id":"2025061001222223918065211458948346","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","out_trade_no":"2025061048985456","total_amount":"0.01","trade_status":"TRADE_SUCCESS","trade_no":"2025061022001465211423945752","auth_app_id":"2021005151606716","receipt_amount":"0.01","point_amount":"0.00","buyer_pay_amount":"0.01","app_id":"2021005151606716","sign_type":"RSA2","seller_id":"2088470188289113"}';
//$parameters = json_decode($parameters,true);



		Factory::setOptions(AlipayService::getOptions());
        $result = Factory::payment()->common()->verifyNotify($parameters);
		if ($result) {
			// 验签成功，处理业务逻辑
		    $out_trade_no = $parameters['out_trade_no'];
		    
		    $order_info = Db::name('course_order')->where('order_sn',$out_trade_no)->find();
		    if(!empty($order_info)){
		        Db::name('course_order')->where('order_sn',$out_trade_no)->update(['pay_type'=>'alipay','trade_no'=>$parameters['trade_no'],'status'=>2,'is_pay'=>1,'pay_time'=>time()]);
		        if($order_info['type']==2 && $order_info['course_id']==1 && !empty($order_info['user_id'])){
		            $member = Db::name("member")->where('id',$order_info['user_id'])->field('id,is_upprofile,year')->find();
		            $valid_days = $member['year'].'-09-01';
			        $valid_time = strtotime($valid_days);
			        Db::name("member")->where('id',$order_info['user_id'])->update(['is_vip'=>1,'valid_time'=>$valid_time]);
		        }
		    }
		    
			setLog('alinotify','success:'.json_encode($parameters));
			echo "success";
		} else {
			// 验签失败
			setLog('alinotify','fail:'.json_encode($parameters));
			echo "fail";
		}
    }
	
	//支付回调
    public function wxnotify(){

        $res_xml = file_get_contents("php://input");
        libxml_disable_entity_loader(true);
        $ret = json_decode(json_encode(simplexml_load_string($res_xml,'simpleXMLElement',LIBXML_NOCDATA)),true);
		
		
		/*$a = '{"appid":"wxaec273f332976f16","attach":"1","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1690148282","nonce_str":"v911j133hiill3zg439cqnxyan7pkgk5","openid":"ou26J5ZS2mh2xd_XvqOYTqqItjC4","out_trade_no":"2025082648525710","result_code":"SUCCESS","return_code":"SUCCESS","sign":"63E74E7193C373EC6F65BCEFA7F9D424","time_end":"20250826231016","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200002832202508268376769291"}';
		$ret = json_decode($a,true);*/
		
        $path = "./log/wxpay/";
        if (!is_dir($path)){
            mkdir($path,0777);  // 创建文件夹test,并给777的权限（所有权限）
        }
        $content = date("Y-m-d H:i:s").'=>'.json_encode($ret,JSON_UNESCAPED_UNICODE).PHP_EOL;  // 写入的内容
        $file = $path."weixin_".date("Ymd").".log";    // 写入的文件
        file_put_contents($file,$content,FILE_APPEND);  // 最简单的快速的以追加的方式写入写入方法，

        $data = array();
        $data['order_sn'] = $ret['out_trade_no'];
        $data['trade_no'] = $ret['transaction_id'];
        $data['total_fee'] = $ret['total_fee'];
        $data['attach'] = $ret['attach'];
        $result = $this->orderhandle($data);
        if (is_array($result)) {
            $xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg>";
            $xml.="</xml>";
            echo $xml;
        }else{
            $contents = 'error => '.json_encode($result,JSON_UNESCAPED_UNICODE).PHP_EOL;  // 写入的内容
            $files = $path."error_".date("Ymd").".log";    // 写入的文件
            file_put_contents($files,$contents,FILE_APPEND);  // 最简单的快速的以追加的方式写入写入方法，
            echo 'fail';
        }
    }
	//回调处理
    public function orderhandle($data){

        $order_sn = trim($data['order_sn']);
        $trade_no = trim($data['trade_no']);
        $total_fee = floatval($data['total_fee']);
        $type = floatval($data['attach']);
		
		$order_info = Db::name('course_order')->where('order_sn',$order_sn)->find();
		if(!empty($order_info)){
			Db::name('course_order')->where('order_sn',$order_sn)->update(['pay_type'=>'wxpay','trade_no'=>$trade_no,'status'=>2,'is_pay'=>1,'pay_time'=>time()]);
			if($order_info['type']==2 && $order_info['course_id']==1 && !empty($order_info['user_id'])){
				$member = Db::name("member")->where('id',$order_info['user_id'])->field('id,is_upprofile,year')->find();
				$valid_days = $member['year'].'-09-01';
				$valid_time = strtotime($valid_days);
				Db::name("member")->where('id',$order_info['user_id'])->update(['is_vip'=>1,'valid_time'=>$valid_time]);
			}
		}else{
			return "找不到订单...";
		}
        return array('status'=>1,'data'=>$data);
    }
}
